<template>
  <div class="main">
    <a-form id="formLogin" ref="formLogin" class="user-layout-login" :model="formState" @finish="onFinish">
      <a-tabs centered>
        <a-tab-pane key="tab1" tab="账号密码登录">
          <a-form-item
            label="账号"
            name="username"
            :rules="[{ required: true, message: '请输入账号' }]"
            validate-trigger="change"
          >
            <a-input v-model:value="formState.username" type="text" placeholder="请输入账号" size="large">
              <template #prefix>
                <UserOutlined />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item
            label="密码"
            name="password"
            :rules="[{ required: true, message: '请输入密码' }]"
            validate-trigger="change"
          >
            <a-input-password v-model:value="formState.password" placeholder="请输入密码" size="large">
              <template #prefix>
                <LockOutlined />
              </template>
            </a-input-password>
          </a-form-item>
        </a-tab-pane>
      </a-tabs>
      <a-form-item>
        <a-checkbox v-model:checked="autoLoginChecked">自动登录</a-checkbox>
      </a-form-item>
      <a-form-item style="margin-top: 24px">
        <a-button
          size="large"
          type="primary"
          html-type="submit"
          class="login-button"
          :loading="loginBtnDisabled"
          :disabled="loginBtnDisabled"
        >
          登录
        </a-button>
      </a-form-item>
      <div class="user-login-other">
        <span>其他登录方式</span>
        <a>
          <WechatOutlined class="item-icon" />
        </a>
        <a>
          <TaobaoOutlined class="item-icon" />
        </a>
        <a>
          <AlipayOutlined class="item-icon" />
        </a>
      </div>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { notification } from 'ant-design-vue';
import type { LoginForm } from '@/api/login/login';
import * as loginApi from '@/api/login/login';
import { SESSION_CACHED_LOGIN_USER, USER_LOGIN } from '@/store/login/loginUser';
import { AlipayOutlined, LockOutlined, TaobaoOutlined, UserOutlined, WechatOutlined } from '@ant-design/icons-vue';
import { ref } from 'vue';
import type { JsonResult } from '@/api';
import { useStoreGlobalStore } from '@/store';

const cachedAutoLoginChecked = 'cachedAutoLoginChecked';
const cachedLoginUser = 'cachedLoginUser';
const cachedLoginPassword = 'cachedLoginPassword';

//自动登录
let autoLoginChecked = ref<boolean>(!!localStorage.getItem(cachedAutoLoginChecked));

/*
 *输入处理
 */
const formState: LoginForm = reactive({
  username: localStorage.getItem(cachedLoginUser) || '',
  password: localStorage.getItem(cachedLoginPassword) || '',
});

/*
 * 登录处理
 */
let loginBtnDisabled = ref(false);
const globalStore = useStoreGlobalStore();
const router = useRouter();

//登录button
async function onFinish() {
  //登录button不可用
  loginBtnDisabled.value = true;
  //登录
  const params = {
    username: formState.username,
    password: formState.password,
  };
  try {
    await loginApi.login(params).then(jsonResult => {
      if (!jsonResult) {
        return;
      }
      //自动登录
      if (autoLoginChecked.value) {
        localStorage.setItem(cachedAutoLoginChecked, cachedAutoLoginChecked);
        localStorage.setItem(cachedLoginUser, params.username);
        localStorage.setItem(cachedLoginPassword, params.password);
      } else {
        localStorage.removeItem(cachedAutoLoginChecked);
        localStorage.removeItem(cachedLoginUser);
        localStorage.removeItem(cachedLoginPassword);
      }

      //登录后处理
      loginSuccess(jsonResult);
    });
  } finally {
    loginBtnDisabled.value = false;
  }
}

//登录成功后处理
function loginSuccess(jsonResult: JsonResult) {
  //保存vuex状态
  globalStore.commit(USER_LOGIN, jsonResult.result);
  sessionStorage.setItem(SESSION_CACHED_LOGIN_USER, JSON.stringify(globalStore.state.loginUser));
  //跳转route
  router.push({ name: 'home' });
  // 延迟 1 秒显示欢迎信息
  setTimeout(() => {
    notification.success({
      message: '欢迎',
      description: `${jsonResult.result.userName},欢迎回来!`,
      duration: 2,
    });
  }, 1000);
}
</script>

<style lang="less" scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>
